﻿using System;
using System.IO;
using System.Web.Mvc;
using CodeCamp.BL;
using System.Text;
using CodeCamp.BL.Model;

namespace CodeCamp.Web.Controllers
{
	public class FileController : CodeCampController
	{
		private const string NO_ATTACHMENT_MESSAGE = "no such attachment found";
		
		public FileContentResult Image(Guid id)
		{
			FileContentResult result;
			Attachment attachment = CodeCampBL.GetAttachment(id);
			if (attachment != null)
			{
				result = new FileContentResult(attachment.Value, attachment.MimeType);
			}
			else
			{
				return new FileContentResult(Encoding.UTF8.GetBytes(NO_ATTACHMENT_MESSAGE), "text/plain");
			}
			return result;
		}


		public FileStreamResult Download(Guid id)
		{
			FileStreamResult result;
			Attachment attachment = CodeCampBL.GetAttachment(id);
			if (attachment != null)
			{
				result = new FileStreamResult(new MemoryStream(attachment.Value), attachment.MimeType)
				         	{
				         		FileDownloadName = attachment.Name
				         	};

			}
			else
			{
				result = new FileStreamResult(new MemoryStream(Encoding.UTF8.GetBytes(NO_ATTACHMENT_MESSAGE)), "text/plain");
			}

			return result;
		}
	}
}


